using System;
using System.Reflection;
using CosyTrade.Core;

namespace CosyTrade.Network
{
    public class MethodInvoke : RemotingObject, IMethodInvoke
    {
        [NonSerialized]
        private static IAddinManager currentAddinManager;
        public static IAddinManager CurrentAddinManager
        {
            get { return currentAddinManager; }
            set { currentAddinManager = value; }
        }

        private object Invoke(string addinName, Type[] paramTypes, string methodName, params object[] arguments)
        {
            IAddin targetAddin = CurrentAddinManager.GetAddin(addinName);
            BindingFlags FindFlags = BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
            MethodInfo invokeMethod = targetAddin.GetType().GetMethod(methodName, FindFlags, null, paramTypes, null);
            return invokeMethod.Invoke(targetAddin, arguments);
        }

        public byte[] Invoke(byte[] requestData)
        {
            Request request = (Request) FormatterHelper.BytesToOBject(requestData);
            Response response;
            try
            {
                object reVal = Invoke(request.AddinKey, request.ArgsTypes, request.MethodName, request.Args);
                response = new Response(reVal, null);
            }
            catch (Exception ex)
            {
                response = new Response(null, new RemotingException(ex.InnerException ?? ex));
            }
            return FormatterHelper.ObjectToBytes(response);
        }
    }
}